import { v1 as uuidv1 } from 'uuid';

export default class BaseWs {
  socket = null; //长连接句柄
  pause = false; //暂停
  uuid = ''; //绝对唯一id
  config = {
    //配置信息
    url: '', //地址
    reconnect: true, //断线是否自动重连
    userId: '', //用户id
    uuid: '', //网页唯一id
    onopen: () => {},
    onmessage: () => {},
    onerror: () => {},
  };

  constructor(config) {
    this.config = { ...this.config, ...config };
    this.uuid = uuidv1();
    this.connect(this.config.url);
  }

  connect(url) {
    this.socket = new WebSocket(url);
    const { socket, config } = this;
    const This = this;

    socket.onopen = () => {
      This.onopen();
      config.onopen();
    };

    socket.onmessage = msg => {
      if(!msg){
        console.log('mmmmmmmmmm')
        return
      }

      const { config } = this;
      if (this.pause) return;
      try {
        
        let rs = JSON.parse(msg.data);
        This.onmessage(rs);
        config.onmessage(rs); 
      } catch (error) {
        console.log(msg.data)
        console.log(error,'666666666')
      }
    };

    socket.onerror = e => {
      This.reconnect(e);
      This.onerror(e);
      config.onerror(e);
    };

    socket.onclose = e => {
      This.reconnect(e);
      This.onclose(e);
      config.onerror(e);
    };
  }

  reconnect(e) {
    const { url, reconnect, socket } = this.config;
    if (reconnect && e.code == 1006 && !this.scoketClose) {
      clearTimeout(this.reconnectTime);
      this.reconnectTime = setTimeout(() => {
        //没连接上会一直重连，设置延迟避免请求过多
        this.connect(url);
      }, 2000);
    }
  }

  /***************************子级覆盖****************************/
  onopen() {}

  onmessage(rs) {}

  onerror(e) {}

  onclose(e) {}

  /***************************原型方法****************************/
  // 关闭长链接
  close() {
    clearTimeout(this.reconnectTime)
    this.socket.close();
    this.socket = null;
    this.scoketClose = true;
  }

  // 发送msg
  sendMsg(msg) {
    if (this.pause) return;
    var val = msg instanceof String ? msg : JSON.stringify(msg);
    socket.send(val);
  }

  /***************************业务方法（公用的）****************************/
}
